<?php

/**
 * ApiController.class.php 
 * 
 *
 * @author     late.xiao@qq.com
 */
namespace Open\Controller;

use Base\Lib\ApiRpc;

class ApiController {

    const API_CODE = 500;
    public function __construct()
    {
        $flag = C('API_OPEN');
        if(!$flag)
        {
            $this->_header404();
            exit;
        }
    }
    public function outside()
    {

        $request = I('request.');
        $format = $request ['format'];
        
        try
        {
            $result = ApiRpc::get('Open')->rpcCall($request ['api_name'], $request ['params']);
            $rs = array(
                    'errcode' => 0, 
                    'errmsg' => 'ok', 
                    'timestamp' => NOW_TIME, 
                    'result' => $result 
            );
        } catch ( \Exception $e )
        {
            
            $msg = $e->getMessage();
            $code = $e->getCode();
            if ($code == self::API_CODE)
            {
                $msg = $request ['api_name'] . ' is not valid';
                $rs ['errcode'] = $code;
                $rs ['errmsg'] = $msg;
                $rs['timestamp'] = NOW_TIME;
                
            }
            else
            {
                return $this->_outFormat($msg, $format);
            }
        }
        
        set_api_result($rs, $format);
        return true;
    }

    protected function _outFormat($result, $format)
    {

        return get_api_result('Open', null, $result, '', $format);
    }
    
    protected function _header404()
    {
        header("HTTP/1.1 404 Not Found");
        header("Status: 404 Not Found");
        exit;
    }
    
    public function __call($method, $params)
    {
         $this->_header404();
         exit;
    }

}
